import { login, getUserInfo } from '@/services/user';
import { message } from 'antd';
import { history } from 'umi';
import { setAuthority, setToken, removeToken } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import userConfig from '../../config/userConfig'
const UserModel = {
  namespace: 'user',
  state: {
    currentUser: {},
    userList: null
  },
  effects: {
    *login({ payload }, { call, put }) {
      console.log(payload, 'payload')
      const response = yield call(login, payload);
      console.log(response, 'aaaaaaaaa')
      if (response.token !== 0) {
        setToken(response.token)
        setAuthority(userConfig[response.admin.type])
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }
        history.replace(redirect || '/');
      } else {
        message.error('用户名或密码错误')
      }
    },

    *getUserInfo(_, { call, put }) {
      const response = yield call(getUserInfo);
      yield put({
        type: 'setState',
        payload: {
          currentUser: response.user
        },
      });
    },
    *logout(_, { call, put }) {
      const { redirect } = getPageQuery(); // Note: There may be security issues, please note
      yield put({ type: 'user/setState', payload: { currentUser: null } })
      removeToken()
      if (window.location.pathname !== '/user/login') {
        history.replace({
          pathname: '/user/login',
          // search: stringify({
          //   redirect: window.location.href,
          // }),
        });
      }
    },
  },
  reducers: {
    setState(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    }
  },

};
export default UserModel;
